using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace CustomPeds
{
    /// <summary>
    /// 日志记录工具类
    /// </summary>
    public static class LogHelper
    {
        private static readonly string LogFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CustomPeds.log");
        private static readonly object LogLock = new object();
        private static bool IsInitialized;

        /// <summary>
        /// 初始化日志系统，清空现有日志内容
        /// </summary>
        public static void InitializeLog()
        {
            if (IsInitialized) return;

            try
            {
                lock (LogLock)
                {
                    // 清空日志文件内容
                    File.WriteAllText(LogFilePath, string.Empty);
                    IsInitialized = true;
                }
            }
            catch (Exception ex)
            {
                // 如果无法创建日志文件，记录到调试输出
                Debug.WriteLine($"无法初始化日志文件: {ex.Message}");
            }
        }

        /// <summary>
        /// 写入日志信息
        /// </summary>
        /// <param name="message">日志消息</param>
        /// <param name="level">日志级别</param>
        public static void WriteLog(string message, LogLevel level = LogLevel.Info)
        {
            try
            {
                lock (LogLock)
                {
                    string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    string logEntry = $"[{timestamp}] [{level}] {message}";
                    
                    // 确保日志目录存在
                    string logDir = Path.GetDirectoryName(LogFilePath);
                    if (!Directory.Exists(logDir))
                    {
                        Directory.CreateDirectory(logDir);
                    }

                    // 追加写入日志
                    File.AppendAllText(LogFilePath, logEntry + Environment.NewLine, Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                // 如果无法写入日志文件，记录到调试输出
                Debug.WriteLine($"无法写入日志: {ex.Message}");
            }
        }

        /// <summary>
        /// 写入异常日志
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="context">异常发生的上下文</param>
        /// <param name="level">日志级别</param>
        public static void WriteException(Exception ex, string context = "", LogLevel level = LogLevel.Error)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                
                if (!string.IsNullOrEmpty(context))
                {
                    sb.AppendLine($"上下文: {context}");
                }
                
                sb.AppendLine($"异常类型: {ex.GetType().Name}");
                sb.AppendLine($"异常消息: {ex.Message}");
                sb.AppendLine($"堆栈跟踪: {ex.StackTrace}");
                
                if (ex.InnerException != null)
                {
                    sb.AppendLine($"内部异常: {ex.InnerException.Message}");
                }
                
                WriteLog(sb.ToString(), level);
            }
            catch
            {
                // 如果日志记录失败，至少记录到调试输出
                Debug.WriteLine($"异常记录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 写入性能日志
        /// </summary>
        /// <param name="operation">操作名称</param>
        /// <param name="elapsedMs">耗时（毫秒）</param>
        public static void WritePerformanceLog(string operation, long elapsedMs)
        {
            string message = $"性能 - {operation}: {elapsedMs}ms";
            WriteLog(message, LogLevel.Performance);
        }

        /// <summary>
        /// 写入调试日志
        /// </summary>
        /// <param name="message">调试消息</param>
        public static void WriteDebug(string message)
        {
            WriteLog(message, LogLevel.Debug);
        }

        /// <summary>
        /// 写入信息日志
        /// </summary>
        /// <param name="message">信息消息</param>
        public static void WriteInfo(string message)
        {
            WriteLog(message);
        }

        /// <summary>
        /// 写入警告日志
        /// </summary>
        /// <param name="message">警告消息</param>
        public static void WriteWarning(string message)
        {
            WriteLog(message, LogLevel.Warning);
        }

        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="message">错误消息</param>
        public static void WriteError(string message)
        {
            WriteLog(message, LogLevel.Error);
        }

        /// <summary>
        /// 写入严重错误日志
        /// </summary>
        /// <param name="message">严重错误消息</param>
        public static void WriteFatal(string message)
        {
            WriteLog(message, LogLevel.Fatal);
        }
    }

    /// <summary>
    /// 日志级别枚举
    /// </summary>
    public enum LogLevel
    {
        Debug,
        Info,
        Performance,
        Warning,
        Error,
        Fatal
    }
}
